package com.gitee.aa76111.tdd.args;

import java.util.Arrays;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.regex.Pattern;

public class Command {
    private static final char PREFIX = '-';
    private static final String SPACE_DIVIDE = "\\s+";
    private HashMap<String, String> map;
    public static final Pattern DIGITPATTERN = Pattern.compile("^[-\\+]?[\\d]+$");
    public Command(String commandLine) {
        map = new HashMap<>();
        ListIterator<String> commandIterator = Arrays.asList(commandLine.trim().split(SPACE_DIVIDE)).listIterator();
        while (commandIterator.hasNext()) {
            String key = commandIterator.next();
            if (isKey(key)) {
                key = key.substring(1);
                if (commandIterator.hasNext()) {
                    String value = commandIterator.next().trim();
                    if (isValue(value)) {
                        map.put(key, value);
                    } else {
                        commandIterator.previous();
                    }
                }
            } else {
                throw new IllegalArgumentException("命令输入错误! 请以 - 开头: " + key);
            }
        }
    }

    private boolean isKey(String key) {
        return key.charAt(0) == PREFIX;
    }

    private boolean isValue(String value) {
        return !isKey(value) || DIGITPATTERN.matcher(value).matches();
    }

    public String getValue(String key) {
        return map.get(key);
    }
}
